from frames import ContoursFrame
from video import Video
import contours
import time
from global_names import *

class Tracker():
	"""
	The Tracker class takes as an input the path to a directory that should contain two sub-directories: 1) video/ , which contains only a series of ordered images representing a movie, and 2) data/ , which contains only a file called data.json . It then generates a Video object containing the video and its associated data. Then, it iterates through the video and extracts one contour per frame according to the parameters specified in the video data file and the methods specified in contours.py . Optional flags include the ability to display this "detection/tracking" as it occurs. After tracking, the object stores all the contour data in a data file, placed into the original directory of the video with a unique timestamp.
	"""
	def __init__(self,video_dir,display=False):
		self.video = Video(video_dir)
		self.display = display
	def track(self):
		self.last_contour = None
		self.selected_contours = []
		self.deltas = []
		
		for frame in self.video.frames:
			self.process_frame(frame)
			
	def process_frame(self, frame):
		contours_frame = ContoursFrame(frame,self.video.params)
		contour_idx, contour = contours.choose_contour(contours_frame.contours, self.last_contour)
		self.selected_contours.append(contour)
		delta = contours.delta_contour(contour,self.last_contour)
		if delta > 0:	
			self.deltas.append(delta)
		self.last_contour = contour
		
		if self.display:
			self.display_frame(contour=contour, window='contour')
			self.display_frame(frame=frame, window='image')
		
	def display_frame(self, frame=None, contour=None, window='window'):
		if contour is None:
			cv2.imshow(window, frame.get_image())
		elif contour is not None:
			contour_img = self.video.empty_frame()
			cv2.drawContours( contour_img, [contour], 0, CD_COLOR, thickness=CD_THICKNESS)
			cv2.imshow(window, contour_img)
			
		k = cv2.waitKey(playback_mspf)
		
	def store_data(self):
		def np2list(array):
			new = []
			for cont in array:
				new.append([])
				for point in cont:
					p = [int(point[0][0]), int(point[0][1])]
					new[-1].append(p)
			return new
		data = {}
		data['timestamp'] = time.time()
		data['parameters'] = self.video.params
		data['contours'] = np2list(self.selected_contours)
		data['deltas'] = self.deltas
		datafile = self.video.name + self.video.shortname + '-' + str(int(data['timestamp'])) + '.json'
		f = open(datafile, 'w')
		f.write("%s" %json.dumps(data))
		print "Data stored in %s"%datafile
		
